<template>
  <!--合同审核-->
  <div class="purchase-check">
    <div style="padding:10px;margin:10px;background:#fff">
      <el-button type="primary" size="small" style="background: #1890ff;border-color: #1890ff" @click="back">返回</el-button>
      <el-select v-model="searchForm.projectId" clearable filterable value-key="id">
        <el-option v-for="item in projects" :key="item.id" :label="item.projectName" :value="item.id"/>
      </el-select>
      <el-select v-model="searchForm.auditStatus" clearable>
        <el-option value="0" label="审核中"/>
        <el-option value="1" label="审核通过"/>
        <el-option value="2" label="审核否决"/>
      </el-select>
      <el-button style="margin-left: 10px" type="primary" icon="el-icon-search" size="small" @click="toSearch">查询</el-button>
    </div>
    <el-card shadow="never" style="margin: 10px;padding: 10px">
      <template #header>合同表</template>
      <a-table
        size="small"
        ref="contracts"
        :data-source="contracts"
        :pagination="pagination"
        :rowKey="record => record.id"
        :customRow="rowClick"
        :loading="contractsLoading"
        :scroll="{ x: 1380 }"
        bordered
      >
        <a-table-column :width="250" :ellipsis="true" key="projectName" title="项目" data-index="projectName" align="center"/>
        <a-table-column key="contractNo" title="合同编号" data-index="contractNo" align="center"/>
        <a-table-column :width="100" key="contractTotalprice" title="合同总价" data-index="contractTotalprice" align="center"/>
        <a-table-column v-for="item in level" :width="100" :key="item.key" :title="item.title" :data-index="item.key" align="center">
          <template slot-scope="text, record">
            <a-popover v-if="text!=null" :title="record.contractNo">
              <template #content>
                审核人：{{users[record[item.type+'Operator']]}}<br>
                审核时间：{{dateFormat(record[item.type+'Time'])}}<br>
                审核备注：{{record[item.type+'Remark']}}<br>
              </template>
              <el-tag :type="status[text]['type']">{{status[text]['text']}}</el-tag>
            </a-popover>
            <el-tag v-else type="info">无需审核</el-tag>
          </template>
        </a-table-column>
        <a-table-column title="附件" align="center">
          <template slot-scope="t">
            <el-tag v-for="(item, key) in t.sysFiles" :key="key" effect="plain" type="primary">
              <a v-on:click.stop="doThis" v-show="item.url" style="display: block" :href="item.url" target="_blank">{{item.name}}</a>
            </el-tag>
          </template>
        </a-table-column>
        <a-table-column :width="100" key="sender" title="送审人" data-index="sender" align="center">
          <template slot-scope="text">
            {{users[text]}}
          </template>
        </a-table-column>
        <a-table-column
          :width="100" key="sendTime" title="送审时间" data-index="sendTime" align="center"
          defaultSortOrder="descend"
          :sorter="(a, b) => a.sendTime-b.sendTime"
        >
          <template slot-scope="text">{{dateFormat(text)}}</template>
        </a-table-column>
        <a-table-column key="sendRemark" title="送审备注" data-index="sendRemark" align="center"/>
        <a-table-column :width="150" key="action" fixed="right" title="操作" align="center">
          <template slot-scope="text, record">
            <div v-if="record[level[page]['key']]==0">
              <el-button type="primary" size="mini" @click.stop="toCheck(record, type=1)">通过</el-button>
              <el-button type="danger" size="mini" @click.stop="toCheck(record, type=2)">否决</el-button>
            </div>
            <div v-else-if="record[level[page]['key']]!=null">
              <el-button type="danger" size="mini" @click.stop="toCheck(record, type=0)">撤销</el-button>
            </div>
            <div v-else>
              <span style="font-style: italic;font-size: 13px">无需审核</span>
            </div>
          </template>
        </a-table-column>
      </a-table>
    </el-card>

    <el-drawer
      title="采购详情"
      :visible.sync="item.drawer"
      direction="rtl"
      size="70%"
    >
      <el-card shadow="never" style="margin-top: 1em">
      <a-table
        size="small"
        ref="items"
        :data-source="items"
        :pagination="item.pagination"
        :rowKey="record => record.id"
        :loading="itemsLoading"
        :scroll="{x:1300, y:windowHeight-250}"
        bordered
      >
        <a-table-column align='center' title="序号" key="sort" data-index="sort" />
        <a-table-column align='center' title="采购项名称" key="item" data-index="item" />
        <a-table-column align='center' title="采购品牌" key="brand" data-index="brand" />
        <a-table-column align='center' title="采购技术参数" key="params" data-index="params" />
        <a-table-column align='center' title="采购型号" key="model" data-index="model" />
        <a-table-column align='center' title="采购数量" key="number" data-index="number" />
        <a-table-column align='center' title="单位" key="unit" data-index="unit" />
        <a-table-column align='center' title="采购单价" key="purchaseSupply.price" data-index="purchaseSupply.price" />
        <a-table-column align='center' title="采购总价" key="purchaseTotalPrice" data-index="purchaseTotalPrice">
          <template slot-scope="text,record">{{parseFloat(record.purchaseSupply.price)*parseFloat(record.number)}}</template>
        </a-table-column>
      </a-table>
    </el-card>
    </el-drawer>
  </div>
</template>

<script>
  import { getAction, postActionByJson, postActionByQueryString } from '@/api/manage'
  import '@/styles/auto-style.css'
  import { getUser } from '@/utils/auth'
  import elDragDialog from '@/directive/el-drag-dialog'
  import { dateFormat} from "@/utils/format";

  export default {
    directives: {elDragDialog},

    data() {
      return {
        drawerId: [],
        pagination: {
          showQuickJumper: true,
          showSizeChanger: true,
          pageSizeOptions: ['10', '20', '50'],
          current: 1,
          pageSize: 10,
          total: 0,
          onChange: (item) => {
          this.pagination.current = item
          this.toSearch()
          },
          onShowSizeChange: (current, pageSize) => {
          this.pagination.pageSize = pageSize
          this.toSearch()
          }, // 改变每页数量时更新显示
        },
        item: {
          drawer: false,
          pagination: {
            showQuickJumper: true,
            showSizeChanger: true,
            pageSizeOptions: ['10', '20', '50'],
            current: 1,
            pageSize: 10,
            total: 0,
            onChange: (item) => {
              this.item.pagination.current = item
              this.loadCheck()
            },
            onShowSizeChange: (current, pageSize) => {
              this.item.pagination.pageSize = pageSize
              this.loadCheck()
            }, // 改变每页数量时更新显示
          },
        },
        page: null,
        level: [
          { audit: 1, title: '一级审核', key: 'firstAudit', type: 'first'},
          { audit: 2, title: '二级审核', key: 'secondAudit', type: 'second'},
          { audit: 3, title: '三级审核', key: 'threeAudit', type: 'three'}
        ],
        status: [
          { type: 'warning', text: '未审核' },
          { type: 'success', text: '通过' },
          { type: 'danger', text: '否决' },
        ],
        searchForm: {auditStatus:'0'},
        projects: [],
        contractsLoading: false,
        contracts: [],
        itemsLoading: false,
        items: [],
        users: {},
        selectedRowKeys: [],
        //实时屏幕高度
        windowHeight: document.documentElement.clientHeight
      }
    },
    created() {
      this.page = this.$route.name == '一级审核' ? 0 : this.$route.name == '二级审核' ? 1 : 2
      this.loadProjects()
      this.loadUserNames()
      if (this.$route.query.projectId) {
        this.receive()
        this.toSearch()
        this.searchForm = []
      }
      this.toSearch()
    },
    methods: {
      doThis(){
        
      },
      receive() {
        this.searchForm.projectId = this.$route.query.projectId
        this.searchForm.auditStatus = this.$route.query.auditStatus
      },
      rowClick(row, index){
        return {
          on: {
            click: () => {
              this.drawerId = row.id
              this.loadCheck()
              this.item.drawer = true
            }
          }
        }
      },
      loadCheck() {
        this.itemsLoading = true
        postActionByQueryString('/purchase/contractManagement/findSupplyByContractId', {
          contractId: this.drawerId,
          pageSize: this.item.pagination.pageSize,
          pageNum: this.item.pagination.current
        }).then(resp => {
          if (resp.data){
            this.items = resp.data.records
            this.item.pagination.current = parseInt(resp.data.current)
            this.item.pagination.pageSize = parseInt(resp.data.size)
            this.item.pagination.total = parseInt(resp.data.total)
          }
        }).catch(()=>{
          this.$message.error('加载失败')
        }).finally(()=>{
          this.itemsLoading = false
        })
      },
      loadUserNames() {
        getAction('/user/findAllIdToName').then(resp=>{
          this.users = resp.data
        })
      },
      toCheck(record, type) {
        let form = {}
        form[this.level[this.page]['key']] =  type
        form['id'] = record.id
        form[this.level[this.page]['type']+'Operator'] = getUser()
        if (type===1) {
          // 撤销
          this.$confirm('是否确定通过审核?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            // 通过
            postActionByQueryString('/purchase/contractAudit/updateContractAuditInfoById', form).then(resp => {
              this.$message({ message: '操作成功', type: 'success' })
              this.toSearch()
            })
          })
        }else if(type===2) {
          // 否决
          this.$prompt('请输入否决备注', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
          }).then(({ value }) => {
            form[this.level[this.page]['type']+'Remark'] = value
            postActionByQueryString('/purchase/contractAudit/updateContractAuditInfoById', form).then(resp=>{
              this.$message({ message: '操作成功', type: 'success' })
              this.toSearch()
            })
          })
        }else if(type===0) {
          // 撤销
          this.$confirm('是否确定撤销审核?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            postActionByQueryString('/purchase/contractAudit/updateContractAuditInfoById', form).then(resp=>{
              this.$message({ message: '操作成功', type: 'success' })
              this.toSearch()
            })
          })
        }
      },
      handleDownload(record) {
        if(record.id){
          getAction('/file/findByOtherId', {otherId: record.id, type: 5}).then(resp=>{
            if (resp.data&&resp.data.length>0) {
              var url = resp.data[0].url
              window.open(url)
            }else {
              this.$message({type: 'warning', message: '文件为空！还未上传文件！'})
            }
          })
        }
      },
      back() {
        this.$router.go(-1)
      },
      loadProjects() {
        getAction('/purchase/project/findAllLike').then(response => {
          this.projects = response.data
        })
      },
      toSearch() {
        this.contractsLoading = true
        this.searchForm.keyWords = this.page
        this.searchForm.pageNum = this.pagination.current,
        this.searchForm.pageSize = this.pagination.pageSize
        postActionByQueryString('/purchase/contract/findByProjectId', this.searchForm)
        .then(resp => {
          if(resp.data){
            this.contracts = resp.data.records
            this.pagination.current = parseInt(resp.data.current)
            this.pagination.pageSize = parseInt(resp.data.size)
            this.pagination.total = parseInt(resp.data.total)
          }
        }).catch(()=>{
          this.$message.error('查询失败')
        }).finally(()=>{
          this.contractsLoading = false
        })
      },
      dateFormat
    }
  }
</script>
